home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / epsilon / sslverify.py < prev    next >
Text File  |  2009-03-13  |  29KB  |  681 lines

  1. # -*- test-case-name: epsilon.test.test_sslverify -*-
  2. # Copyright 2005 Divmod, Inc.  See LICENSE file for details
  3.  
  4. import warnings
  5. warnings.warn(
  6.     "Use twisted.internet.ssl instead of epsilon.sslverify.",
  7.     category=DeprecationWarning)
  8.  
  9. import itertools, md5
  10. from OpenSSL import SSL, crypto
  11.  
  12. from twisted.python import reflect
  13. from twisted.internet.defer import Deferred
  14.  
  15. # Private - shared between all ServerContextFactories, counts up to
  16. # provide a unique session id for each context
  17. _sessionCounter = itertools.count().next
  18.  
  19. class _SSLApplicationData(object):
  20.     def __init__(self):
  21.         self.problems = []
  22.  
  23. class VerifyError(Exception):
  24.     """Could not verify something that was supposed to be signed.
  25.     """
  26.  
  27. class PeerVerifyError(VerifyError):
  28.     """The peer rejected our verify error.
  29.     """
  30.  
  31. class OpenSSLVerifyError(VerifyError):
  32.  
  33.     _errorCodes = {0: ('X509_V_OK', 'ok', 'the operation was successful. >'),
  34.                    2: ('X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT',
  35.                        'unable to get issuer certificate',
  36.                        "the issuer certificate could not be found', 'this occurs if the issuer certificate of an untrusted certificate cannot be found."),
  37.                    3: ('X509_V_ERR_UNABLE_TO_GET_CRL',
  38.                        ' unable to get certificate CRL',
  39.                        'the CRL of a certificate could not be found. Unused.'),
  40.                    4: ('X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE',
  41.                        "unable to decrypt certificate's signature",
  42.                        'the certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not match- ing the expected value, this is only meaningful for RSA keys.'),
  43.                    5: ('X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE',
  44.                        "unable to decrypt CRL's signature",
  45.                        "the CRL signature could not be decrypted', 'this means that the actual signature value could not be determined rather than it not matching the expected value. Unused."),
  46.                    6: ('X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY',
  47.                        'unable to decode issuer',
  48.                        'public key the public key in the certificate SubjectPublicKeyInfo could not be read.'),
  49.                    7: ('X509_V_ERR_CERT_SIGNATURE_FAILURE',
  50.                        'certificate signature failure',
  51.                        'the signature of the certificate is invalid.'),
  52.                    8: ('X509_V_ERR_CRL_SIGNATURE_FAILURE',
  53.                        'CRL signature failure',
  54.                        'the signature of the certificate is invalid. Unused.'),
  55.                    9: ('X509_V_ERR_CERT_NOT_YET_VALID',
  56.                        'certificate is not yet valid',
  57.                        "the certificate is not yet valid', 'the notBefore date is after the cur- rent time."),
  58.                    10: ('X509_V_ERR_CERT_HAS_EXPIRED',
  59.                         'certificate has expired',
  60.                         "the certificate has expired', 'that is the notAfter date is before the current time."),
  61.                    11: ('X509_V_ERR_CRL_NOT_YET_VALID',
  62.                         'CRL is not yet valid',
  63.                         'the CRL is not yet valid. Unused.'),
  64.                    12: ('X509_V_ERR_CRL_HAS_EXPIRED',
  65.                         'CRL has expired',
  66.                         'the CRL has expired. Unused.'),
  67.                    13: ('X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD',
  68.                         "format error in certificate's",
  69.                         'notBefore field the certificate notBefore field contains an invalid time.'),
  70.                    14: ('X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD',
  71.                         "format error in certificate's",
  72.                         'notAfter field the certificate notAfter field contains an invalid time.'),
  73.                    15: ('X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD',
  74.                         "format error in CRL's lastUpdate field",
  75.                         'the CRL lastUpdate field contains an invalid time. Unused.'),
  76.                    16: ('X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD',
  77.                         "format error in CRL's nextUpdate field",
  78.                         'the CRL nextUpdate field contains an invalid time. Unused.'),
  79.                    17: ('X509_V_ERR_OUT_OF_MEM',
  80.                         'out of memory',
  81.                         'an error occurred trying to allocate memory. This should never happen.'),
  82.                    18: ('X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT',
  83.                         'self signed certificate',
  84.                         'the passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates.'),
  85.                    19: ('X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN',
  86.                         'self signed certificate in certificate chain',
  87.                         'the certificate chain could be built up using the untrusted certificates but the root could not be found locally.'),
  88.                    20: ('X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
  89.                         'unable to get local issuer',
  90.                         'certificate the issuer certificate of a locally looked up certificate could not be found. This normally means the list of trusted certificates is not com- plete.'),
  91.                    21: ('X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE',
  92.                         'unable to verify the first',
  93.                         'certificate no signatures could be verified because the chain contains only one cer- tificate and it is not self signed.'),
  94.                    22: ('X509_V_ERR_CERT_CHAIN_TOO_LONG',
  95.                         'certificate chain too long',
  96.                         'the certificate chain length is greater than the supplied maximum depth. Unused.'),
  97.                    23: ('X509_V_ERR_CERT_REVOKED',
  98.                         'certificate revoked',
  99.                         'the certificate has been revoked. Unused.'),
  100.                    24: ('X509_V_ERR_INVALID_CA',
  101.                         'invalid CA certificate',
  102.                         'a CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose.'),
  103.                    25: ('X509_V_ERR_PATH_LENGTH_EXCEEDED',
  104.                         'path length constraint exceeded',
  105.                         'the basicConstraints pathlength parameter has been exceeded.'),
  106.                    26: ('X509_V_ERR_INVALID_PURPOSE',
  107.                         'unsupported certificate purpose',
  108.                         'the supplied certificate cannot be used for the specified purpose.'),
  109.                    27: ('X509_V_ERR_CERT_UNTRUSTED',
  110.                         'certificate not trusted',
  111.                         'the root CA is not marked as trusted for the specified purpose.'),
  112.                    28: ('X509_V_ERR_CERT_REJECTED',
  113.                         'certificate rejected',
  114.                         'the root CA is marked to reject the specified purpose.'),
  115.                    29: ('X509_V_ERR_SUBJECT_ISSUER_MISMATCH',
  116.                         'subject issuer mismatch',
  117.                         'the current candidate issuer certificate was rejected because its sub- ject name did not match the issuer name of the current certificate. Only displayed when the -issuer_checks option is set.'),
  118.                    30: ('X509_V_ERR_AKID_SKID_MISMATCH',
  119.                         'authority and subject key identifier mismatch',
  120.                         'the current candidate issuer certificate was rejected because its sub- ject key identifier was present and did not match the authority key identifier current certificate. Only displayed when the -issuer_checks option is set.'),
  121.                    31: ('X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH',
  122.                         'authority and issuer serial number mismatch',
  123.                         'the current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. Only displayed when the -issuer_checks option is set.'),
  124.                    32: ('X509_V_ERR_KEYUSAGE_NO_CERTSIGN',
  125.                         'key usage does not include certificate',
  126.                         'signing the current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing.'),
  127.                    50: ('X509_V_ERR_APPLICATION_VERIFICATION',
  128.                         'application verification failure',
  129.                         'an application specific error. Unused.')}
  130.  
  131.  
  132.     def __init__(self, cert, errno, depth):
  133.         VerifyError.__init__(self, cert, errno, depth)
  134.         self.cert = cert
  135.         self.errno = errno
  136.         self.depth = depth
  137.  
  138.     def __repr__(self):
  139.         x = self._errorCodes.get(self.errno)
  140.         if x is not None:
  141.             name, short, long = x
  142.             return 'Peer Certificate Verification Failed: %s (error code: %d)' % (
  143.                 long, self.errno
  144.                 )
  145.  
  146.     __str__ = __repr__
  147.  
  148. _x509namecrap = [
  149.     ['CN', 'commonName'],
  150.     ['O',  'organizationName'],
  151.     ['OU', 'organizationalUnitName'],
  152.     ['L',  'localityName'],
  153.     ['ST', 'stateOrProvinceName'],
  154.     ['C',  'countryName'],
  155.     [      'emailAddress']]
  156.  
  157. _x509names = {}
  158.  
  159.  
  160. for abbrevs in _x509namecrap:
  161.     for abbrev in abbrevs:
  162.         _x509names[abbrev] = abbrevs[0]
  163.  
  164. class DistinguishedName(dict):
  165.     __slots__ = ()
  166.     def __init__(self, **kw):
  167.         for k, v in kw.iteritems():
  168.             setattr(self, k, v)
  169.  
  170.     def _copyFrom(self, x509name):
  171.         d = {}
  172.         for name in _x509names:
  173.             value = getattr(x509name, name, None)
  174.             if value is not None:
  175.                 setattr(self, name, value)
  176.  
  177.     def _copyInto(self, x509name):
  178.         for k, v in self.iteritems():
  179.             setattr(x509name, k, v)
  180.  
  181.     def __repr__(self):
  182.         return '<DN %s>' % (dict.__repr__(self)[1:-1])
  183.  
  184.     def __getattr__(self, attr):
  185.         return self[_x509names[attr]]
  186.  
  187.     def __setattr__(self, attr, value):
  188.         assert type(attr) is str
  189.         if not attr in _x509names:
  190.             raise AttributeError("%s is not a valid OpenSSL X509 name field" % (attr,))
  191.         realAttr = _x509names[attr]
  192.         value = value.encode('ascii')
  193.         assert type(value) is str
  194.         self[realAttr] = value
  195.  
  196.     def inspect(self):
  197.         l = []
  198.         from formless.annotate import nameToLabel
  199.         lablen = 0
  200.         for kp in _x509namecrap:
  201.             k = kp[-1]
  202.             label = nameToLabel(k)
  203.             lablen = max(len(label), lablen)
  204.             l.append((label, getattr(self, k)))
  205.         lablen += 2
  206.         for n, (label, attr) in enumerate(l):
  207.             l[n] = (label.rjust(lablen)+': '+ attr)
  208.         return '\n'.join(l)
  209.  
  210. DN = DistinguishedName
  211.  
  212. class CertBase:
  213.     def __init__(self, original):
  214.         self.original = original
  215.  
  216.     def _copyName(self, suffix):
  217.         dn = DistinguishedName()
  218.         dn._copyFrom(getattr(self.original, 'get_'+suffix)())
  219.         return dn
  220.  
  221.     def getSubject(self):
  222.         return self._copyName('subject')
  223.  
  224.  
  225.  
  226. def problemsFromTransport(tpt):
  227.     """Return a list of L{OpenSSLVerifyError}s given a Twisted transport object.
  228.     """
  229.     return tpt.getHandle().get_context().get_app_data().problems
  230.  
  231. class Certificate(CertBase):
  232.     def __repr__(self):
  233.         return '<%s Subject=%s Issuer=%s>' % (self.__class__.__name__,
  234.                                               self.getSubject().commonName,
  235.                                               self.getIssuer().commonName)
  236.  
  237.     def __eq__(self, other):
  238.         if isinstance(other, Certificate):
  239.             return self.dump() == other.dump()
  240.         return False
  241.  
  242.     def __ne__(self, other):
  243.         return not self.__eq__(other)
  244.  
  245.     def load(Class, requestData, format=crypto.FILETYPE_ASN1, args=()):
  246.         return Class(crypto.load_certificate(format, requestData), *args)
  247.     load = classmethod(load)
  248.     _load = load
  249.  
  250.     def dumpPEM(self):
  251.         """Dump both public and private parts of a private certificate to PEM-format
  252.         data
  253.         """
  254.         return self.dump(crypto.FILETYPE_PEM)
  255.  
  256.     def loadPEM(Class, data):
  257.         """Load both private and public parts of a private certificate from a chunk of
  258.         PEM-format data.
  259.         """
  260.         return Class.load(data, crypto.FILETYPE_PEM)
  261.     loadPEM = classmethod(loadPEM)
  262.  
  263.     def peerFromTransport(Class, transport):
  264.         return Class(transport.getHandle().get_peer_certificate())
  265.     peerFromTransport = classmethod(peerFromTransport)
  266.  
  267.     def hostFromTransport(Class, transport):
  268.         return Class(transport.getHandle().get_host_certificate())
  269.     hostFromTransport = classmethod(hostFromTransport)
  270.  
  271.     def getPublicKey(self):
  272.         return PublicKey(self.original.get_pubkey())
  273.  
  274.     def dump(self, format=crypto.FILETYPE_ASN1):
  275.         return crypto.dump_certificate(format, self.original)
  276.  
  277.     def serialNumber(self):
  278.         return self.original.get_serial_number()
  279.  
  280.     def digest(self, method='md5'):
  281.         return self.original.digest(method)
  282.  
  283.     def _inspect(self):
  284.         return '\n'.join(['Certificate For Subject:',
  285.                           self.getSubject().inspect(),
  286.                           '\nIssuer:',
  287.                           self.getIssuer().inspect(),
  288.                           '\nSerial Number: %d' % self.serialNumber(),
  289.                           'Digest: %s' % self.digest()])
  290.  
  291.     def inspect(self):
  292.         return '\n'.join(self._inspect(), self.getPublicKey().inspect())
  293.  
  294.     def getIssuer(self):
  295.         return self._copyName('issuer')
  296.  
  297.     def options(self, *authorities):
  298.         raise NotImplementedError('Possible, but doubtful we need this yet')
  299.  
  300. class CertificateRequest(CertBase):
  301.     def load(Class, requestData, requestFormat=crypto.FILETYPE_ASN1):
  302.         req = crypto.load_certificate_request(requestFormat, requestData)
  303.         dn = DistinguishedName()
  304.         dn._copyFrom(req.get_subject())
  305.         if not req.verify(req.get_pubkey()):
  306.             raise VerifyError("Can't verify that request for %r is self-signed." % (dn,))
  307.         return Class(req)
  308.     load = classmethod(load)
  309.  
  310.     def dump(self, format=crypto.FILETYPE_ASN1):
  311.         return crypto.dump_certificate_request(format, self.original)
  312.  
  313. class PrivateCertificate(Certificate):
  314.     def __repr__(self):
  315.         return Certificate.__repr__(self) + ' with ' + repr(self.privateKey)
  316.  
  317.     def _setPrivateKey(self, privateKey):
  318.         if not privateKey.matches(self.getPublicKey()):
  319.             raise VerifyError(
  320.                 "Sanity check failed: Your certificate was not properly signed.")
  321.         self.privateKey = privateKey
  322.         return self
  323.  
  324.     def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
  325.         return self.load(newCertData, self.privateKey, format)
  326.  
  327.     def load(Class, data, privateKey, format=crypto.FILETYPE_ASN1):
  328.         return Class._load(data, format)._setPrivateKey(privateKey)
  329.     load = classmethod(load)
  330.  
  331.     def inspect(self):
  332.         return '\n'.join([Certificate._inspect(self),
  333.                           self.privateKey.inspect()])
  334.  
  335.     def dumpPEM(self):
  336.         """Dump both public and private parts of a private certificate to PEM-format
  337.         data
  338.         """
  339.         return self.dump(crypto.FILETYPE_PEM) + self.privateKey.dump(crypto.FILETYPE_PEM)
  340.  
  341.     def loadPEM(Class, data):
  342.         """Load both private and public parts of a private certificate from a chunk of
  343.         PEM-format data.
  344.         """
  345.         return Class.load(data, KeyPair.load(data, crypto.FILETYPE_PEM),
  346.                           crypto.FILETYPE_PEM)
  347.  
  348.     loadPEM = classmethod(loadPEM)
  349.  
  350.     def fromCertificateAndKeyPair(Class, certificateInstance, privateKey):
  351.         privcert = Class(certificateInstance.original)
  352.         return privcert._setPrivateKey(privateKey)
  353.     fromCertificateAndKeyPair = classmethod(fromCertificateAndKeyPair)
  354.  
  355.     def options(self, *authorities):
  356.         options = dict(privateKey=self.privateKey.original,
  357.                        certificate=self.original)
  358.         if authorities:
  359.             options.update(dict(verify=True,
  360.                                 requireCertificate=True,
  361.                                 caCerts=[auth.original for auth in authorities]))
  362.         return OpenSSLCertificateOptions(**options)
  363.  
  364.     def certificateRequest(self, format=crypto.FILETYPE_ASN1,
  365.                            digestAlgorithm='md5'):
  366.         return self.privateKey.certificateRequest(
  367.             self.getSubject(),
  368.             format,
  369.             digestAlgorithm)
  370.  
  371.     def signCertificateRequest(self,
  372.                                requestData,
  373.                                verifyDNCallback,
  374.                                serialNumber,
  375.                                requestFormat=crypto.FILETYPE_ASN1,
  376.                                certificateFormat=crypto.FILETYPE_ASN1):
  377.         issuer = self.getSubject()
  378.         return self.privateKey.signCertificateRequest(
  379.             issuer,
  380.             requestData,
  381.             verifyDNCallback,
  382.             serialNumber,
  383.             requestFormat,
  384.             certificateFormat)
  385.  
  386.  
  387.     def signRequestObject(self, certificateRequest, serialNumber,
  388.                           secondsToExpiry=60 * 60 * 24 * 365, # One year
  389.                           digestAlgorithm='md5'):
  390.         return self.privateKey.signRequestObject(self.getSubject(),
  391.                                                  certificateRequest,
  392.                                                  serialNumber,
  393.                                                  secondsToExpiry,
  394.                                                  digestAlgorithm)
  395.  
  396. class PublicKey:
  397.     def __init__(self, osslpkey):
  398.         self.original = osslpkey
  399.         req1 = crypto.X509Req()
  400.         req1.set_pubkey(osslpkey)
  401.         self._emptyReq = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, req1)
  402.  
  403.     def matches(self, otherKey):
  404.         return self._emptyReq == otherKey._emptyReq
  405.  
  406. # O OG OMG OMFG PYOPENSSL SUCKS SO BAD
  407. #     def verifyCertificate(self, certificate):
  408. #         """returns None, or raises a VerifyError exception if the certificate could not
  409. #         be verified.
  410. #         """
  411. #         if not certificate.original.verify(self.original):
  412. #             raise VerifyError("We didn't sign that certificate.")
  413.  
  414.     def __repr__(self):
  415.         return '<%s %s>' % (self.__class__.__name__, self.keyHash())
  416.  
  417.     def keyHash(self):
  418.         """MD5 hex digest of signature on an empty certificate request with this key.
  419.         """
  420.         return md5.md5(self._emptyReq).hexdigest()
  421.  
  422.     def inspect(self):
  423.         return 'Public Key with Hash: %s' % (self.keyHash(),)
  424.  
  425.  
  426. class KeyPair(PublicKey):
  427.  
  428.     def load(Class, data, format=crypto.FILETYPE_ASN1):
  429.         return Class(crypto.load_privatekey(format, data))
  430.     load = classmethod(load)
  431.  
  432.     def dump(self, format=crypto.FILETYPE_ASN1):
  433.         return crypto.dump_privatekey(format, self.original)
  434.  
  435.     def __getstate__(self):
  436.         return self.dump()
  437.  
  438.     def __setstate__(self, state):
  439.         self.__init__(crypto.load_privatekey(crypto.FILETYPE_ASN1, state))
  440.  
  441.     def inspect(self):
  442.         t = self.original.type()
  443.         if t == crypto.TYPE_RSA:
  444.             ts = 'RSA'
  445.         elif t == crypto.TYPE_DSA:
  446.             ts = 'DSA'
  447.         else:
  448.             ts = '(Unknown Type!)'
  449.         L = (self.original.bits(), ts, self.keyHash())
  450.         return '%s-bit %s Key Pair with Hash: %s' % L
  451.  
  452.     def generate(Class, kind=crypto.TYPE_RSA, size=1024):
  453.         pkey = crypto.PKey()
  454.         pkey.generate_key(kind, size)
  455.         return Class(pkey)
  456.  
  457.     def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
  458.         return PrivateCertificate.load(newCertData, self, format)
  459.  
  460.     generate = classmethod(generate)
  461.  
  462.     def requestObject(self, distinguishedName, digestAlgorithm='md5'):
  463.         req = crypto.X509Req()
  464.         req.set_pubkey(self.original)
  465.         distinguishedName._copyInto(req.get_subject())
  466.         req.sign(self.original, digestAlgorithm)
  467.         return CertificateRequest(req)
  468.  
  469.     def certificateRequest(self, distinguishedName,
  470.                            format=crypto.FILETYPE_ASN1,
  471.                            digestAlgorithm='md5'):
  472.         """Create a certificate request signed with this key.
  473.  
  474.         @return: a string, formatted according to the 'format' argument.
  475.         """
  476.         return self.requestObject(distinguishedName, digestAlgorithm).dump(format)
  477.  
  478.  
  479.  
  480.     def signCertificateRequest(self,
  481.                                issuerDistinguishedName,
  482.                                requestData,
  483.                                verifyDNCallback,
  484.                                serialNumber,
  485.                                requestFormat=crypto.FILETYPE_ASN1,
  486.                                certificateFormat=crypto.FILETYPE_ASN1,
  487.                                secondsToExpiry=60 * 60 * 24 * 365, # One year
  488.                                digestAlgorithm='md5'):
  489.         """Given a blob of certificate request data and a certificate authority's
  490.         DistinguishedName, return a blob of signed certificate data.
  491.  
  492.         If verifyDNCallback returns a Deferred, I will return a Deferred which
  493.         fires the data when that Deferred has completed.
  494.         """
  495.         hlreq = CertificateRequest.load(requestData, requestFormat)
  496.  
  497.         dn = hlreq.getSubject()
  498.         vval = verifyDNCallback(dn)
  499.  
  500.         def verified(value):
  501.             if not value:
  502.                 raise VerifyError("DN callback %r rejected request DN %r" % (verifyDNCallback, dn))
  503.             return self.signRequestObject(issuerDistinguishedName, hlreq,
  504.                                           serialNumber, secondsToExpiry, digestAlgorithm).dump(certificateFormat)
  505.  
  506.         if isinstance(vval, Deferred):
  507.             return vval.addCallback(verified)
  508.         else:
  509.             return verified(vval)
  510.  
  511.  
  512.     def signRequestObject(self,
  513.                           issuerDistinguishedName,
  514.                           requestObject,
  515.                           serialNumber,
  516.                           secondsToExpiry=60 * 60 * 24 * 365, # One year
  517.                           digestAlgorithm='md5'):
  518.         """
  519.         Sign a CertificateRequest instance, returning a Certificate instance.
  520.         """
  521.         req = requestObject.original
  522.         dn = requestObject.getSubject()
  523.         cert = crypto.X509()
  524.         issuerDistinguishedName._copyInto(cert.get_issuer())
  525.         cert.set_subject(req.get_subject())
  526.         cert.set_pubkey(req.get_pubkey())
  527.         cert.gmtime_adj_notBefore(0)
  528.         cert.gmtime_adj_notAfter(secondsToExpiry)
  529.         cert.set_serial_number(serialNumber)
  530.         cert.sign(self.original, digestAlgorithm)
  531.         return Certificate(cert)
  532.  
  533.     def selfSignedCert(self, serialNumber, **kw):
  534.         dn = DN(**kw)
  535.         return PrivateCertificate.fromCertificateAndKeyPair(
  536.             self.signRequestObject(dn, self.requestObject(dn), serialNumber),
  537.             self)
  538.  
  539.  
  540. class OpenSSLCertificateOptions(object):
  541.     """A factory for SSL context objects, for server SSL connections.
  542.     """
  543.  
  544.     _context = None
  545.     # Older versions of PyOpenSSL didn't provide OP_ALL.  Fudge it here, just in case.
  546.     _OP_ALL = getattr(SSL, 'OP_ALL', 0x0000FFFF)
  547.  
  548.     method = SSL.TLSv1_METHOD
  549.  
  550.     def __init__(self,
  551.                  privateKey=None,
  552.                  certificate=None,
  553.                  method=None,
  554.                  verify=False,
  555.                  caCerts=None,
  556.                  verifyDepth=9,
  557.                  requireCertificate=True,
  558.                  verifyOnce=True,
  559.                  enableSingleUseKeys=True,
  560.                  enableSessions=True,
  561.                  fixBrokenPeers=False):
  562.         """
  563.         Create an OpenSSL context SSL connection context factory.
  564.  
  565.         @param privateKey: A PKey object holding the private key.
  566.  
  567.         @param certificate: An X509 object holding the certificate.
  568.  
  569.         @param method: The SSL protocol to use, one of SSLv23_METHOD,
  570.         SSLv2_METHOD, SSLv3_METHOD, TLSv1_METHOD.  Defaults to TLSv1_METHOD.
  571.  
  572.         @param verify: If True, verify certificates received from the peer and
  573.         fail the handshake if verification fails.  Otherwise, allow anonymous
  574.         sessions and sessions with certificates which fail validation.  By
  575.         default this is False.
  576.  
  577.         @param caCerts: List of certificate authority certificates to
  578.         send to the client when requesting a certificate.  Only used if verify
  579.         is True, and if verify is True, either this must be specified or
  580.         caCertsFile must be given.  Since verify is False by default,
  581.         this is None by default.
  582.  
  583.         @param verifyDepth: Depth in certificate chain down to which to verify.
  584.         If unspecified, use the underlying default (9).
  585.  
  586.         @param requireCertificate: If True, do not allow anonymous sessions.
  587.  
  588.         @param verifyOnce: If True, do not re-verify the certificate
  589.         on session resumption.
  590.  
  591.         @param enableSingleUseKeys: If True, generate a new key whenever
  592.         ephemeral DH parameters are used to prevent small subgroup attacks.
  593.  
  594.         @param enableSessions: If True, set a session ID on each context.  This
  595.         allows a shortened handshake to be used when a known client reconnects.
  596.  
  597.         @param fixBrokenPeers: If True, enable various non-spec protocol fixes
  598.         for broken SSL implementations.  This should be entirely safe,
  599.         according to the OpenSSL documentation, but YMMV.  This option is now
  600.         off by default, because it causes problems with connections between
  601.         peers using OpenSSL 0.9.8a.
  602.         """
  603.  
  604.         assert (privateKey is None) == (certificate is None), "Specify neither or both of privateKey and certificate"
  605.         self.privateKey = privateKey
  606.         self.certificate = certificate
  607.         if method is not None:
  608.             self.method = method
  609.  
  610.         self.verify = verify
  611.         assert ((verify and caCerts) or
  612.                 (not verify)), "Specify client CA certificate information if and only if enabling certificate verification"
  613.  
  614.         self.caCerts = caCerts
  615.         self.verifyDepth = verifyDepth
  616.         self.requireCertificate = requireCertificate
  617.         self.verifyOnce = verifyOnce
  618.         self.enableSingleUseKeys = enableSingleUseKeys
  619.         self.enableSessions = enableSessions
  620.         self.fixBrokenPeers = fixBrokenPeers
  621.  
  622.     def __getstate__(self):
  623.         d = super(OpenSSLCertificateOptions, self).__getstate__()
  624.         try:
  625.             del d['context']
  626.         except KeyError:
  627.             pass
  628.         return d
  629.  
  630.     def getContext(self):
  631.         """Return a SSL.Context object.
  632.         """
  633.         if self._context is None:
  634.             self._context = self._makeContext()
  635.         return self._context
  636.  
  637.     def _makeContext(self):
  638.         ctx = SSL.Context(self.method)
  639.         ctx.set_app_data(_SSLApplicationData())
  640.  
  641.         if self.certificate is not None and self.privateKey is not None:
  642.             ctx.use_certificate(self.certificate)
  643.             ctx.use_privatekey(self.privateKey)
  644.             # Sanity check
  645.             ctx.check_privatekey()
  646.  
  647.         verifyFlags = SSL.VERIFY_NONE
  648.         if self.verify:
  649.             verifyFlags = SSL.VERIFY_PEER
  650.             if self.requireCertificate:
  651.                 verifyFlags |= SSL.VERIFY_FAIL_IF_NO_PEER_CERT
  652.             if self.verifyOnce:
  653.                 verifyFlags |= SSL.VERIFY_CLIENT_ONCE
  654.             if self.caCerts:
  655.                 store = ctx.get_cert_store()
  656.                 for cert in self.caCerts:
  657.                     store.add_cert(cert)
  658.  
  659.         def _trackVerificationProblems(conn,cert,errno,depth,preverify_ok):
  660.             # retcode is the answer OpenSSL's default verifier would have
  661.             # given, had we allowed it to run.
  662.             if not preverify_ok:
  663.                 ctx.get_app_data().problems.append(OpenSSLVerifyError(cert, errno, depth))
  664.             return preverify_ok
  665.         ctx.set_verify(verifyFlags, _trackVerificationProblems)
  666.  
  667.         if self.verifyDepth is not None:
  668.             ctx.set_verify_depth(self.verifyDepth)
  669.  
  670.         if self.enableSingleUseKeys:
  671.             ctx.set_options(SSL.OP_SINGLE_DH_USE)
  672.  
  673.         if self.fixBrokenPeers:
  674.             ctx.set_options(self._OP_ALL)
  675.  
  676.         if self.enableSessions:
  677.             sessionName = md5.md5("%s-%d" % (reflect.qual(self.__class__), _sessionCounter())).hexdigest()
  678.             ctx.set_session_id(sessionName)
  679.  
  680.         return ctx
  681.